<?php

namespace app\admin\controller;

use app\common\controller\publics\Jwt;
use think\Controller;
use think\Db;
use think\Request;
use think\facade\Cache;
use think\Model;

class Models extends Controller
{
    public function initialize()
    {
        //token 验证登录信息是否有效
        //设置跨域头
        header('Access-Control-Allow-Origin: *');
        $request = new Request();
        $g=$request->get();
        $p=$request->post();
        $token = '';
        (isset($g['token']) && !empty($g['token'])) and ($token = $g['token']);
        (isset($p['token']) && !empty($p['token'])) and ($token = $p['token']);
        if(empty($token)){
            js_code('
                    var str = localStorage.getItem("token");
                    if(str !=="" || str.length>0){
                        var preg = /(\?token=.*|\?.*)/i
                        var href = location.href.replace(preg,"");
                        location.href=(href+"?token="+localStorage.getItem("token")).replace(/[?]{2,}/g,"?");
                    }else{
                        location.href="/admin_login_out";
                    }   
               ');
        }
        $jwt = new \app\common\controller\publics\Jwt();
        if(!$jwt->is_token($g['token']) || empty(cookie('fwf_admin_name'))){
            $this->error('信息验证错误，请重新登录','/admin_login_out');
        }
    }

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //
    }

    public function model_list(){
        //检查权限
        power_check();
        //获取菜单
        $mca=['m'=>\think\facade\Request::module(),'c'=>\think\facade\Request::controller(),'a'=>\think\facade\Request::action()];
        $mca['mca'] = $mca['m'].'/'.$mca['c'].'/'.$mca['a'];
        $mca['ca'] = $mca['c'].'/'.$mca['a'];
        $new_menu = Cache::tag('menu')->get('menu');
        $this->assign('new_menu',$new_menu);
        $this->assign('mca',$mca);

        $this->assign('title',lang('model_list'));
        $model_list = Db::name('model')->select();
        $this->assign('model_list',$model_list);

        return $this->fetch();

    }
    public function model_edit(Request $request){
        //检查权限
        power_check();
        //获取菜单
        $mca=['m'=>\think\facade\Request::module(),'c'=>\think\facade\Request::controller(),'a'=>\think\facade\Request::action()];
        $mca['mca'] = $mca['m'].'/'.$mca['c'].'/'.$mca['a'];
        $mca['ca'] = $mca['c'].'/'.$mca['a'];
        $new_menu = Cache::tag('menu')->get('menu');
        $this->assign('new_menu',$new_menu);
        $this->assign('mca',$mca);


        $id = $request->param('id');
        $t = lang('model_add');
        if($id){
            $t = lang('model_edit');
        }
        $this->assign('title',$t);
        //获取模型信息
        $model = Db::name('model')->where('model_id','=',$id)->find();
        //模型字段列表 （field_pid 为 0）
        $model_field_list = Db::name('model_field')->where('field_pid','=',0)->select();
        $this->assign('model_field_list',$model_field_list);
        //获取菜单信息
        $menu_list = Db::name('menu')->where('menu_id','in',[32])->whereOr('menu_pid','in',[32])->select();
        $GLOBALS['tree']['pid'] = 'menu_pid';
        $GLOBALS['tree']['id'] = 'menu_id';
        $menu_list = get_leval_list(32,1,$menu_list);
        $this->assign('menu_list',$menu_list);


        $k1 = 'field_name'; $k2='field_alias'; $k3='field_desc'; $k4='checked'; $k5='field_pid';
        $model_fields = [
            [$k1 => 'media_id', $k2 => '', $k3 => '媒体内容编号', $k4 => 1],
            [$k1 => 'media_title', $k2 => '', $k3 => '媒体内容标题', $k4 => 0],
            [$k1 => 'meida_add_time', $k2 => '', $k3 => '添加时间(自动生成)', $k4 => 0],
            [$k1 => 'meida_img', $k2 => '', $k3 => '封面图片地址', $k4 => 0],
            [$k1 => 'media_desc', $k2 => '', $k3 => '简介(多行文本)', $k4 => 0],
            [$k1 => 'media_content', $k2 => '', $k3 => '内容，富文本', $k4 => 0],
            [$k1 => 'media_order', $k2 => '', $k3 => '排序，越大越靠前', $k4 => 0],
            [$k1 => 'media_recom', $k2 => '', $k3 => '是否推荐', $k4 => 0],
            [$k1 => 'media_model_id', $k2 => '', $k3 => '模型表id', $k4 => 1],
            [$k1 => 'media_member_id', $k2 => '', $k3 => '管理员id', $k4 => 1],
            [$k1 => 'media_category_id', $k2 => '', $k3 => '栏目id', $k4 => 0],
        ];

        if(!in_array($model['model_field_id'],[0,'',null])){
            $model_fields_former = unserialize($model['model_fields']);

            //从模型字段表读取的字段数据 (表的字段信息)
            foreach ($model_field_list as $key => $item) {
                if($item['field_id'] == $model['model_field_id']){
                    $model_fields = Db::name('model_field')->where('field_pid','=',$model['model_field_id'])->order(['order'=>'desc'])->select();
                    break;
                }
            }
            if( is_array($model_fields_former) ){
                foreach ($model_fields as $key => $item) {
                    foreach ($model_fields_former as $k => $v) {
                        if($v[$k1] == $item[$k1] && $v[$k5] == $item[$k5]){
                            $model_fields[$key][$k1] = $v[$k1];
                            $model_fields[$key][$k2] = $v[$k2];
                            $model_fields[$key][$k3] = $v[$k3];
                            $model_fields[$key][$k4] = $v[$k4];
                            unset($model_fields_former[$k]);
                        }
                    }
                }
            }
        }else{
            if(!empty($model['model_fields'])){
                $model_fields = unserialize($model['model_fields']);
            }
        }

        $this->assign('model',$model);
        $this->assign('model_fields',$model_fields);

        return $this->fetch();
    }
    public function model_save(Request $request){
        //检查权限
        power_check();
        $p = $request->post();
        $id = $p['model_id'];
        $admin_id = cookie('fwf_admin_id');
        $validate = new \app\admin\validate\Models();
        if(!$validate->model_save($p)){
            $err = $validate->getError();
            $this->error(array_shift($err));
        }else{
            $k1 = 'field_name'; $k2='field_alias'; $k3='field_desc'; $k4='checked';
            $data=[
                'model_name'        =>$p['model_name'],
                'model_field_id'    =>$p['model_field_id'],
                'model_action'      =>$p['model_action'],
            ];
            $checkeds = ['media_title','media_model_id','media_member_id'];
            if(isset($p['fields']) && is_array($p['fields'])){
                foreach ($p['fields'] as $key => $value) {
                    if(!isset($value[$k4]) || empty($value[$k4]) ){
                        $p['fields'][$key][$k4] = 0;
                    }
                    if(in_array($value[$k1],$checkeds)){
                        $p['fields'][$key][$k4] = 1;
                    }
                }
            }
            $model_fields = serialize($p['fields']);
            $data['model_fields'] = $model_fields;
            if($id){
                //修改
                $up_n = Db::name('model')->where('model_id','=',$id)->data($data)->update();
                if($up_n){
                    fwf_log('修改模型信息，模型ID：'.$id.'，操作管理员ID:'.$admin_id.'，影响的行数：'.$up_n);
                }
                $this->success(lang('edit_success'),'/models/model_edit/id/'.$id.'/?token='.$p['token']);
            }else{
                //添加

                $insert_id = Db::name('model')->insertGetId($data);
                if($insert_id){
                    fwf_log('添加模型信息，添加的管理员ID：'.$insert_id.'，操作管理员ID:'.$admin_id);
                    $this->success(lang('add_success'),'/Models/model_list/id/'.$insert_id.'/?token='.$p['token']);
                }

                $this->error(lang('add_fail'),'/Models/model_list/?token='.$p['token']);
            }
        }

    }
    public function model_del(Request $request){
        //检查权限
        power_check();

        $id = $request->param('id');
        if($id){
            $del_n = Db::name('model')->where('model_id','=',$id)->delete();
            if($del_n){
                fwf_log('删除模型，删除的模型ID：'.$id.'，删除的行数：'.$del_n);
                $this->redirect(lang('url').'/Models/model_list');
            }
        }
        $this->error(lang('del_fail'));
    }
    public function model_edit_ajax(Request $request){
        //检查权限
        $ok=power_check(1);
        $g = $request->get();
        $admin_id = cookie('fwf_admin_id');
        if($ok){
            if($g['id']!='' && $g['f'] && $g['v']){
                $up_n = Db::name('model')->where('model_id','=',$g['id'])->data([ $g['f'] => $g['v'] ])->update();
                if($up_n){
                    fwf_log('异步修改模型信息，修改的ID：'.$g['id'].'，修改的字段：'.$g['f'].'，操作管理员ID：'.$admin_id);
                    return_json(1,1,lang('edit_success'));
                }
            }
        }
        return_json(0,2,lang('edit_fail'));
    }


    public function model_field_list(Request $request){
        //检查权限
        power_check();
        //获取菜单
        $mca=['m'=>\think\facade\Request::module(),'c'=>\think\facade\Request::controller(),'a'=>\think\facade\Request::action()];
        $mca['mca'] = $mca['m'].'/'.$mca['c'].'/'.$mca['a'];
        $mca['ca'] = $mca['c'].'/'.$mca['a'];
        $new_menu = Cache::tag('menu')->get('menu');
        $this->assign('new_menu',$new_menu);
        $this->assign('mca',$mca);

        $this->assign('title',lang('model_field_list'));

        $model_field_list = Db::name('model_field')->order(['order'=>'desc'])->select();
        if(is_array($model_field_list) && count($model_field_list)>0){
            $GLOBALS['tree']['id'] = 'field_id';
            $GLOBALS['tree']['pid'] = 'field_pid';
            $model_field_list = get_leval_list(1,1,$model_field_list);
        }

        $this->assign('model_field_list',$model_field_list);
        return $this->fetch();
    }
    public function model_field_edit(Request $request){
        //检查权限
        power_check();
        //获取菜单
        $mca=['m'=>\think\facade\Request::module(),'c'=>\think\facade\Request::controller(),'a'=>\think\facade\Request::action()];
        $mca['mca'] = $mca['m'].'/'.$mca['c'].'/'.$mca['a'];
        $mca['ca'] = $mca['c'].'/'.$mca['a'];
        $new_menu = Cache::tag('menu')->get('menu');
        $this->assign('new_menu',$new_menu);
        $this->assign('mca',$mca);

        $id = $request->param('id');
        $t = lang('model_field_add');
        if($id){
            $t = lang('model_field_edit');
        }
        $this->assign('title',$t);

        $model_field = Db::name('model_field')->where('field_id','=',$id)->find();
        $model_field_list = Db::name('model_field')->where('field_pid','=',0)->select();

        $this->assign('model_field',$model_field);
        $this->assign('model_field_list',$model_field_list);
        return $this->fetch();
    }
    public function model_field_save(Request $request){
        //检查权限
        power_check();
        $p = $request->post();
        $id = $p['field_id'];
        $admin_id = cookie('fwf_admin_id');
        $validate = new \app\admin\validate\Models();
        if(!$validate->model_field_save($p)){
            $err = $validate->getError();
            $this->error(array_shift($err));
        }else{
            $data = [
                'field_pid'     =>$p['field_pid'],
                'field_name'    =>$p['field_name'],
                'field_alias'   =>$p['field_alias'],
                'field_desc'    =>$p['field_desc'],
                'checked'       =>$p['checked'],
                'order'         =>$p['order'],
            ];
            if($id){
                //修改
                $up_n = Db::name('model_field')->where('field_id','=',$id)->data($data)->update();
                if ($up_n){
                    fwf_log('修改模型字段，修改的ID：'.$id.'，操作管理员ID：'.$admin_id.'，影响的行数：'.$up_n);
                }
                $this->success(lang('edit_success'),'/Models/model_field_edit/id/'.$id.'/?token='.$p['token']);
            }else{
                //添加
                $insert_id = Db::name('model_field')->insertGetId($data);
                if($insert_id){
                    fwf_log('添加模型字段，添加的ID：'.$insert_id.'，操作管理员ID：'.$admin_id);
                    $this->success(lang('add_success'),'/Models/model_field_list/id/'.$insert_id.'/?token='.$p['token']);
                }
                $this->error(lang('add_fail'),'/Models/model_field_list/?token='.$p['token']);
            }
        }
    }
    public function model_field_del(Request $request){
        //检查权限
        power_check();

        $id = $request->param('id');
        if($id){
            $del_n = Db::name('model_field')->where('field_id','=',$id)->delete();
            if($del_n){
                fwf_log('删除模型字段，删除的模型字段ID：'.$id.'，删除的行数：'.$del_n);
                $this->redirect(lang('url').'/Models/model_field_list');
            }
        }
        $this->error(lang('del_fail'));
    }
    public function model_field_edit_ajax(Request $request){
        //检查权限
        $ok=power_check(1);
        $g = $request->get();
        $admin_id = cookie('fwf_admin_id');
        if($ok){
            if($g['id']!='' && $g['f'] && $g['v']){
                $up_n = Db::name('model_field')->where('field_id','=',$g['id'])->data([ $g['f'] => $g['v'] ])->update();
                if($up_n){
                    fwf_log('异步修改模型字段信息，修改的ID：'.$g['id'].'，修改的字段：'.$g['f'].'，操作管理员ID：'.$admin_id);
                    return_json(1,1,lang('edit_success'));
                }
            }
        }
        return_json(0,2,lang('edit_fail'));
    }


}
